package com.kuangstudy.controller;

import com.kuangstudy.constant.RedisConstants;
import com.kuangstudy.entity.ShopCart;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author panghu
 * @version 1.0.0
 * @createTime 2023年09月17日 11:08:00
 * @Description
 */
@Slf4j
@Controller
@Api(tags = "购物车业务")
public class ShopCartController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/shopcard")
    public String toShopCard() {
        return "shopcart";
    }

    /**
     * 模拟像购物车中添加商品
     * @param shopCart
     * @return
     */
    @ResponseBody
    @PostMapping("/hash/shopcart/add")
    @ApiOperation("模拟像购物车中添加商品")
    public ShopCart addShopCard(@RequestBody ShopCart shopCart) {
        // 定义用户用户的购物车的key
        String shopCardKey = RedisConstants.USER_SHOP_CART + shopCart.getUserid();
        Long productId = shopCart.getProductid();

        // 判断购物车是否存在
        Boolean hasKey = redisTemplate.opsForHash().hasKey(shopCardKey, productId.toString());
        if (!hasKey) {
            // 如果该商品在购物车中不存在   将购物车的数据放入到hash数据结构中
            redisTemplate.opsForHash().put(shopCardKey, productId.toString(), shopCart);
            // 设置购物车的过期时间
            redisTemplate.expire(shopCardKey, 30L, TimeUnit.DAYS);
        }else {
            // 获取hash中的商品信息 进行数量+1
            ShopCart shopCarts = (ShopCart)redisTemplate.opsForHash().get(shopCardKey, productId.toString());
            shopCarts.setProductnum(shopCarts.getProductnum() + 1);
            redisTemplate.opsForHash().put(shopCardKey, productId.toString(),shopCarts);
            // 数量+1 重置 购物车的过期时间
            redisTemplate.expire(shopCardKey, 30L, TimeUnit.DAYS);
        }

        // 添加成功返回即可
        return shopCart;
    }


    /**
     * 修改购物车中商品的数量
     */
    @ResponseBody
    @PostMapping("/hash/shopcart/update")
    @ApiOperation("修改购物车中商品的数量")
    public ShopCart updateShopcartnum(Long userId,Long productId,Integer productnum){
        // 1: 存储购物车的缓存key
        String shopCartKey = RedisConstants.USER_SHOP_CART + userId.toString();
        // 2：修改购物车的数量  获取hash中的商品信息 进行数量+1
        ShopCart shopCarts = (ShopCart)redisTemplate.opsForHash().get(shopCartKey, productId.toString());
        shopCarts.setProductnum(shopCarts.getProductnum() + productnum);
        redisTemplate.opsForHash().put(shopCartKey, productId.toString(),shopCarts);
        // 数量+1 重置 购物车的过期时间
        redisTemplate.expire(shopCartKey, 30L, TimeUnit.DAYS);
        return shopCarts;
    }

    /**
     * 删除购物车的某个商品
     * @param userId
     * @param productId
     * @return
     */
    @ResponseBody
    @PostMapping("/hash/shopcart/del")
    @ApiOperation("删除购物车的某个商品")
    public String delshopcart(Long userId, Long productId) {
        // 1: 存储购物车的缓存key
        String shopCartKey = RedisConstants.USER_SHOP_CART + userId.toString();
        // 2：修改购物车的数量
        this.redisTemplate.opsForHash().delete(shopCartKey, productId.toString());
        return "success";
    }


    /**
     * 查询购物车中的所有的商品的信息
     * @param userId 用户id
     * @return
     */
    @ResponseBody
    @GetMapping("/hash/shopcart/selectall")
    @ApiOperation("查询购物车中的所有的商品的信息")
    public Map<String, Object> selectshopcart(Long userId) {
        // 1: 存储购物车的缓存key
        String shopCartKey = RedisConstants.USER_SHOP_CART + userId.toString();
        // 2: 从redis中获取商品的总条数
        Long size = redisTemplate.opsForHash().size(shopCartKey);
        // 3：从redis中获取购物车中所有的商品 获取到hgetall shopcartKey  2 map 1 map 3 map
        Map<String,ShopCart> shopCartMap = redisTemplate.opsForHash().entries(shopCartKey);
        // 4: 计算总金额
        double totalmoney = 0d;
        List<ShopCart> shopCartList = new ArrayList<>();
        for (Map.Entry<String, ShopCart> entry : shopCartMap.entrySet()) {
            shopCartList.add(entry.getValue());
            totalmoney += Integer.parseInt(String.valueOf(entry.getValue().getProductnum())) *
                    Double.parseDouble(String.valueOf(entry.getValue().getProductprice()));
        }

        // 6: 返回购物车的数据
        Map<String, Object> hashMap = new HashMap<>();
        // 商品的总计
        hashMap.put("totalPrice",totalmoney);
        // 这个商品的个数
        hashMap.put("totalCount",size);
        // 具体商品的数据
        hashMap.put("resultList",shopCartList);
        return hashMap;
    }
}
